package com.ruoyi.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.ruoyi.bill.domain.MaterialIOVo;
import com.ruoyi.bill.domain.ZnDepotHead;
import com.ruoyi.bill.domain.ZnDepotItem;
import com.ruoyi.bill.mapper.ZnDepotHeadMapper;
import com.ruoyi.bill.service.IZnDepotHeadService;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.material.domain.ZnMaterialInitialStock;
import com.ruoyi.material.mapper.ZnMaterialMapper;
import com.ruoyi.material.service.IZnMaterialInitialStockService;
import com.ruoyi.system.domain.ZnProfitDetail;
import com.ruoyi.system.domain.ZnProfitHistory;
import com.ruoyi.system.mapper.ZnProfitDetailMapper;
import com.ruoyi.system.mapper.ZnProfitHistoryMapper;
import com.ruoyi.system.service.IZnProfitDetailService;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.expression.spel.ast.NullLiteral;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Service
public class ProfitTask extends Thread {

    public final static Logger log = LoggerFactory.getLogger(ProfitTask.class);
    @Autowired
    private ZnDepotHeadMapper znDepotHeadMapper;
    @Autowired
    private ZnProfitDetailMapper znProfitDetailMapper;
    @Autowired
    private ZnProfitHistoryMapper znProfitHistoryMapper;
    @Autowired
    private IZnMaterialInitialStockService znMaterialInitialStockService;
    private Long profitId;

    private Long tenanId;

    private ZnDepotHead queryParam ;

    @Autowired
    private IZnProfitDetailService znProfitDetailService;

    public ProfitTask() {

    }

    public ProfitTask(IZnProfitDetailService znProfitDetailService,Long profitId, Long tenanId) {
        super();
        this.znProfitDetailService = znProfitDetailService;
        this.profitId = profitId;
        this.tenanId = tenanId;
    }
    public ProfitTask(Long profitId, Long tenanId) {
        super();
        this.profitId = profitId;
        this.tenanId = tenanId;
    }
    public ProfitTask(IZnProfitDetailService znProfitDetailService,ZnDepotHeadMapper znDepotHeadMapper, ZnProfitDetailMapper znProfitDetailMapper, ZnProfitHistoryMapper znProfitHistoryMapper, IZnMaterialInitialStockService znMaterialInitialStockService,ZnDepotHead queryParam, Long profitId, Long tenanId) {
        super();
        this.znProfitDetailService = znProfitDetailService;
        this.znDepotHeadMapper =znDepotHeadMapper;
        this.znProfitHistoryMapper = znProfitHistoryMapper;
        this.znProfitDetailMapper = znProfitDetailMapper;
        this.znMaterialInitialStockService = znMaterialInitialStockService;
        this.queryParam = queryParam;
        this.profitId = profitId;
        this.tenanId = tenanId;
    }

//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public void run() {
//        try {
//
//        boolean flag = !Thread.currentThread().isInterrupted();
//        if(flag){
//            String threadName = Thread.currentThread().getName();
//            System.out.println(threadName + " is running");
//            queryParam.setTenantId(tenanId);
//            queryParam.setDeleteFlag("0");
//            //查询销售单
//            queryParam.setType("出库");
//            queryParam.setSubType("销售");
//            queryParam.setStatus("2");
//            //todo 临时使用
//            //        queryParam.getParams().put("endOperTime",DateUtils.getTime());
//            queryParam.getParams().put("endOperTime","2022-06-30 23:59:59");
//            queryParam.getParams().put("orderSort","asc");
//            List<ZnDepotHead> znDepotHeadList = znDepotHeadMapper.selectZnDepotHeadList(queryParam);
//            List<ZnProfitDetail> dataList = new ArrayList<ZnProfitDetail>();
//            Map<String,ZnMaterialInitialStock> initStockMap = new HashMap<>();//初始库存数量
//            List<String> saveKey = new ArrayList<>();
//            List<String> redisKeyList = new ArrayList<>();
////            System.out.println(JSON.toJSONString(znDepotHeadList));
//            //TODO  临时过滤掉不统计商品
//            List<Long> lsMaterialIdList = new ArrayList<>();
////            lsMaterialIdList.add(198l);//TODO 没有采购商品 198
////            lsMaterialIdList.add(378l);//TODO 静腌西冷牛排 有初始库存,没采购记录，如何处理？
////            lsMaterialIdList.add(556l);//TODO 礼盒包装 报溢入库，没采购记录，如何处理？
////            lsMaterialIdList.add(395l);//TODO 395 海霸王汤圆 有初始库存，没采购记录
//
//            List<Long> nullStockMaterialIdList = new ArrayList<>();
//            Map<String,List<MaterialIOVo>> materialMap = new HashMap<>();
//            ZnProfitDetail znProfitDetail = new ZnProfitDetail();
//            znProfitDetail.setTenantId(tenanId);
//            for (ZnDepotHead znDepotHead:znDepotHeadList) {
//                if(flag){
//                    ZnDepotItem znDepotItemQuery = new ZnDepotItem();
//                    znDepotItemQuery.setHeaderId(znDepotHead.getId());
//                    znDepotItemQuery.setTenantId(znDepotHead.getTenantId());
//                    List<ZnDepotItem> itemList = znDepotHeadMapper.selectZnDepotItemList(znDepotItemQuery);
//                    for (ZnDepotItem znDepotItem:itemList) {
////                        if(flag && znDepotItem.getBasicNumber().compareTo(BigDecimal.ZERO)>0 && znDepotHead.getId() ==395 && znDepotItem.getId()==7463){
//                        if(flag && znDepotItem.getBasicNumber().compareTo(BigDecimal.ZERO)>0 ){
//                            //1、判断商品是否在不统计的名单中、判断当前订单中的商品中已经计算过，就不在计算
//                            if(lsMaterialIdList.contains(znDepotItem.getMaterialId()) || saveKey.contains(znDepotHead.getId()+"-"+znDepotItem.getId())){
//                                continue;
//                            }
//                            //TODO 多单位
//                            if(znDepotItem.getUnitRatio()>1){//多单位，非基本单位
//
//                            }else{
//                                znProfitDetail.setMaterialExtendId(znDepotItem.getMaterialExtendId());
//                                queryParam.getParams().put("materialExtendId",znDepotItem.getMaterialExtendId());
//                            }
//                            String initStockKey = znDepotItem.getDepotId()+"_"+znDepotItem.getMaterialId();
//                            znProfitDetail = new ZnProfitDetail();
//                            znProfitDetail.setProfitId(profitId);
//                            znProfitDetail.setTenantId(tenanId);
//                            znProfitDetail.setDepotId(znDepotItem.getDepotId());
//                            znProfitDetail.setCustomerId(znDepotHead.getOrganId());
//                            znProfitDetail.setMaterialId(znDepotItem.getMaterialId());
//                            znProfitDetail.setMaterialExtendId(znDepotItem.getMaterialExtendId());
//                            znProfitDetail.setOutHeadId(znDepotHead.getId());
//                            znProfitDetail.setOutOperTime(znDepotHead.getOperTime());
//                            znProfitDetail.setOutItemId(znDepotItem.getId());
//                            znProfitDetail.setType(1);
//
//                            //2、先看是否有初始库存，有的先扣初始库存
//                            if(initStockMap.containsKey(initStockKey)){
//                                ZnMaterialInitialStock initStock = initStockMap.get(initStockKey);
//                                znProfitDetail.setInitStockId(initStock.getId());
//                                if(initStock.getNumber().compareTo(BigDecimal.ZERO)>0){
//                                    int compareResult = znDepotItem.getBasicNumber().compareTo(initStock.getNumber());
//                                    if(compareResult<=0){//订单数据小于等于初始库存，将扣除的剩余继续保存到map中
//                                        znProfitDetail.setBasicNumber(znDepotItem.getBasicNumber());
//                                        znProfitDetail.setOutPrice(znDepotItem.getBasicNumber().multiply(znDepotItem.getUnitPrice()));
//                                        znProfitDetail.setInPrice(znDepotItem.getBasicNumber().multiply(initStock.getPrice()));
//                                        initStock.setNumber(initStock.getNumber().subtract(znDepotItem.getBasicNumber()).abs());
//                                        initStockMap.put(initStockKey,initStock);
//                                        znDepotItem.setBasicNumber(BigDecimal.ZERO);
//                                        continue;
//                                    }else {//订单数量大于初始库存
//                                        znProfitDetail.setBasicNumber(initStock.getNumber());
//                                        znProfitDetail.setOutPrice(initStock.getNumber().multiply(znDepotItem.getUnitPrice()));
//                                        znProfitDetail.setInPrice(initStock.getNumber().multiply(initStock.getPrice()));
//                                        initStock.setNumber(BigDecimal.ZERO);
//                                        initStockMap.put(initStockKey,initStock);
//                                        znDepotItem.setBasicNumber(znDepotItem.getBasicNumber().subtract(initStock.getNumber()).abs());
//                                    }
//                                    znProfitDetail.setProfit(znProfitDetail.getOutPrice().subtract(znProfitDetail.getInPrice()));
//                                    dataList.add(znProfitDetail);
//                                }
//                            }else{
//                                ZnMaterialInitialStock znMaterialInitialStock = new ZnMaterialInitialStock();
//                                znMaterialInitialStock.setMaterialId(znDepotItem.getMaterialId());
//                                znMaterialInitialStock.setTenantId(tenanId);
//                                znMaterialInitialStock.setDeleteFlag("0");
//                                znMaterialInitialStock.setDepotId(znDepotItem.getDepotId());
//                                znMaterialInitialStock.getParams().put("gtNumber",0);//初始库存大于0
//                                List<ZnMaterialInitialStock> znMaterialInitialStockList =  znMaterialInitialStockService.selectZnMaterialInitialStockList(znMaterialInitialStock);
//                                if(znMaterialInitialStockList.size()>0){
//                                    ZnMaterialInitialStock initStock = znMaterialInitialStockList.get(0);
//                                    znProfitDetail.setInitStockId(initStock.getId());
//                                    if(initStock.getPrice()==null){
//                                        ZnProfitHistory znProfitHistory = new ZnProfitHistory();
//                                        znProfitHistory.setId(profitId);
//                                        znProfitHistory.setState(2);
//                                        znProfitHistory.setResult(znDepotHead.getId()+"_"+znDepotItem.getId()+"—商品："+znDepotItem.getMaterialName()+"(货号:"+znDepotItem.getBarCode()+"）初始库存价格为空，请先填写上价格再重新计算");
//                                        znProfitHistoryMapper.updateZnProfitHistory(znProfitHistory);
//                                        Thread.currentThread().interrupt();
//                                        System.out.println(threadName+"已中断0");
//                                        flag = false;
//                                        break;
//                                    }
//                                    int compareResult = znDepotItem.getBasicNumber().compareTo(initStock.getNumber());
//                                    if(compareResult<=0){
//                                        znProfitDetail.setBasicNumber(znDepotItem.getBasicNumber());
//                                        znProfitDetail.setOutPrice(znProfitDetail.getBasicNumber().multiply(znDepotItem.getUnitPrice()));
//                                        znProfitDetail.setInPrice(znProfitDetail.getBasicNumber().multiply(initStock.getPrice()));
//                                        initStock.setNumber(initStock.getNumber().subtract(znDepotItem.getBasicNumber()).abs());
//                                        initStockMap.put(initStockKey,initStock);
//                                        znDepotItem.setBasicNumber(BigDecimal.ZERO);
//                                    }else{
//                                        znProfitDetail.setBasicNumber(initStock.getNumber());
//                                        znProfitDetail.setOutPrice(initStock.getNumber().multiply(znDepotItem.getUnitPrice()));
//                                        znProfitDetail.setInPrice(initStock.getNumber().multiply(initStock.getPrice()));
//                                        initStock.setNumber(BigDecimal.ZERO);
//                                        initStockMap.put(initStockKey,initStock);
//                                    }
//                                    znProfitDetail.setProfit(znProfitDetail.getOutPrice().subtract(znProfitDetail.getInPrice()));
//                                    dataList.add(znProfitDetail);
//                                }
//                            }
//                            //3、当扣除初始库存之后，还有数量则从入库单据中，逐一进行扣。
//                            if(znDepotItem.getBasicNumber().compareTo(BigDecimal.ZERO)>0){
//                                String key = "pandian_"+tenanId+"_"+znDepotItem.getMaterialId();
//                                List<MaterialIOVo> materialIOVos =  materialMap.get(key);
//                                if(materialIOVos ==null && !nullStockMaterialIdList.contains(znDepotItem.getMaterialId())){
//                                    Map<String,Object> tempMap = znProfitDetailMapper.findLastOperTimeAndInId(znProfitDetail);
//                                    if(tempMap !=null){
//                                        if(tempMap.containsKey("in_head_id")){
//                                            if(tempMap.get("in_head_id") !=null){
//                                                queryParam.getParams().put("gtId",Long.valueOf(tempMap.get("in_head_id").toString()));
//                                            }
//                                        }
//                                    }
//                                    queryParam.setType("入库");
////                                queryParam.setSubType("采购");
//                                    queryParam.setStatus("2");//已入库
//                                    queryParam.getParams().put("materialId",znDepotItem.getMaterialId());
//                                    queryParam.getParams().put("depotId",znDepotItem.getDepotId());
//                                    materialIOVos =  znDepotHeadMapper.selectMaterialPurchaseInList(queryParam);
//                                }
//                                if(materialIOVos == null ){
////                            System.out.println("库存不足订单："+JSON.toJSONString(znDepotHead));
////                            System.out.println("库存不足商品信息："+JSON.toJSONString(znDepotItem));
//                                    ZnProfitHistory znProfitHistory = new ZnProfitHistory();
//                                    znProfitHistory.setId(profitId);
//                                    znProfitHistory.setState(2);
//                                    znProfitHistory.setResult("商品："+znDepotItem.getMaterialName()+"("+znDepotItem.getBarCode()+"）库存不足，请先采购再重新计算");
//                                    znProfitHistoryMapper.updateZnProfitHistory(znProfitHistory);
//                                    Thread.currentThread().interrupt();
//                                    System.out.println(threadName+"已中断1");
//                                    flag = false;
//                                    break;
//                                    //                        return AjaxResult.error("商品："+znDepotItem.getMaterialName()+"("+znDepotItem.getBarCode()+"）库存不足，请先采购再继续计算");
//                                }else{
//                                    Double orderNumber = znDepotItem.getBasicNumber().doubleValue();
//                                    if (orderNumber > 0 ) {
////                                if (orderNumber > 0 ) {
//                                        int nextIndex  = 0;
//                                        for (int i=0;i<materialIOVos.size();i++){
//                                            znProfitDetail = new ZnProfitDetail();
//                                            znProfitDetail.setType(0);
//                                            znProfitDetail.setProfitId(profitId);
//                                            znProfitDetail.setTenantId(tenanId);
//                                            znProfitDetail.setDepotId(znDepotItem.getDepotId());
//                                            znProfitDetail.setCustomerId(znDepotHead.getOrganId());
//                                            znProfitDetail.setMaterialId(znDepotItem.getMaterialId());
//                                            znProfitDetail.setMaterialExtendId(znDepotItem.getMaterialExtendId());
//                                            znProfitDetail.setOutHeadId(znDepotHead.getId());
//                                            znProfitDetail.setOutOperTime(znDepotHead.getOperTime());
//                                            znProfitDetail.setOutItemId(znDepotItem.getId());
//                                            MaterialIOVo materialIOVo = materialIOVos.get(i);
//                                            orderNumber = orderNumber - materialIOVo.getBasicNumber().doubleValue();
//                                            if(orderNumber <= 0 ){
//                                                znProfitDetail.setInHeadId(materialIOVo.getInHeadId());
//                                                znProfitDetail.setInItemId(materialIOVo.getInItemId());
//                                                if(orderNumber==0){
//                                                    znProfitDetail.setBasicNumber(materialIOVo.getBasicNumber());
//                                                    nextIndex = i+1;
//                                                }else{//当商品的数量过多，修改为多余的数量
//                                                    nextIndex = i;
//                                                    znProfitDetail.setBasicNumber(materialIOVo.getBasicNumber().subtract(new BigDecimal(orderNumber)));
//                                                    materialIOVo.setBasicNumber(new BigDecimal(orderNumber).abs());
//                                                }
//                                                znProfitDetail.setOutPrice(znDepotItem.getUnitPrice().multiply(znProfitDetail.getBasicNumber()));
//                                                znProfitDetail.setInPrice(znProfitDetail.getBasicNumber().multiply(materialIOVo.getUnitPrice()));
//                                                znProfitDetail.setProfit(znProfitDetail.getOutPrice().subtract(znProfitDetail.getInPrice()));
//                                                dataList.add(znProfitDetail);
//                                                saveKey.add(znProfitDetail.getOutHeadId()+"-"+znProfitDetail.getOutItemId());
//                                                break;
//                                            }else{
//                                                if(i<materialIOVos.size()){
//                                                    znProfitDetail.setBasicNumber(materialIOVo.getBasicNumber());
//                                                    znProfitDetail.setInHeadId(materialIOVo.getInHeadId());
//                                                    znProfitDetail.setInItemId(materialIOVo.getInItemId());
//                                                    znProfitDetail.setOutPrice(znDepotItem.getUnitPrice().multiply(znProfitDetail.getBasicNumber()));
//                                                    znProfitDetail.setInPrice(materialIOVo.getBasicNumber().multiply(materialIOVo.getUnitPrice()));
//                                                    znProfitDetail.setProfit(znProfitDetail.getOutPrice().subtract(znProfitDetail.getInPrice()));
//                                                    dataList.add(znProfitDetail);
//                                                    saveKey.add(znProfitDetail.getOutHeadId()+"-"+znProfitDetail.getOutItemId());
//                                                }else{
//                                                    //                                        return AjaxResult.error("商品："+znDepotItem.getMaterialName()+"("+znDepotItem.getBarCode()+"）库存不足，请先采购再继续计算");
//                                                    ZnProfitHistory znProfitHistory = new ZnProfitHistory();
//                                                    znProfitHistory.setId(profitId);
//                                                    znProfitHistory.setState(2);
//                                                    znProfitHistory.setResult("商品："+znDepotItem.getMaterialName()+"("+znDepotItem.getBarCode()+"）库存不足，请先采购再重新计算");
//                                                    znProfitHistoryMapper.updateZnProfitHistory(znProfitHistory);
//                                                    Thread.currentThread().interrupt();
//                                                    System.out.println("商品："+znDepotItem.getMaterialName()+"("+znDepotItem.getMaterialId()+"）库存不足，请先采购再重新计算");
////                                                System.out.println(threadName+"已中断");
//                                                    flag = false;
//                                                    break;
//                                                }
//                                            }
//                                        }
//                                        List<MaterialIOVo> temp = new ArrayList<>();
//                                        if(nextIndex<materialIOVos.size()){
//                                            temp =  materialIOVos.subList(nextIndex,materialIOVos.size());
//                                            materialMap.put(key,temp);
//                                        }else{
//                                            nullStockMaterialIdList.add(znDepotItem.getMaterialId());
//                                            materialMap.remove(key);
//                                            System.out.println(key+","+nextIndex+","+JSON.toJSONString(materialIOVos.subList(nextIndex,materialIOVos.size())));
//                                        }
//                                    }
//                                }
//                            }
//                        }
//                    }
//                }
//            }
//            if(flag){
//                int batchInsertCount = 0;
//                ZnProfitHistory znProfitHistory = new ZnProfitHistory();
//                znProfitHistory.setId(profitId);
//                System.out.println(JSON.toJSONString(dataList));
//                if(dataList.size()>0){
//                    batchInsertCount =  znProfitDetailMapper.batchInsertZnProfitDetail(dataList);
//                    if(initStockMap.size()>0){
//                        for (Map.Entry<String,ZnMaterialInitialStock> entry:initStockMap.entrySet()) {
//                            ZnMaterialInitialStock znMaterialInitialStock = new ZnMaterialInitialStock();
//                            znMaterialInitialStock.setId(entry.getValue().getId());
//                            znMaterialInitialStock.setIsProfit("1");
//                            znMaterialInitialStockService.updateZnMaterialInitialStock(znMaterialInitialStock);
//                        }
//                    }
//                    znProfitHistory.setResult("利润计算成功！");
//                    znProfitHistory.setState(1);
//                }else{
////                return AjaxResult.success("没有有效的计算单据！");
//                    znProfitHistory.setState(2);
//                    znProfitHistory.setResult("没有有效的计算单据！");
//                }
//                znProfitHistoryMapper.updateZnProfitHistory(znProfitHistory);
//                Thread.currentThread().interrupt();
//                System.out.println(threadName + " is exit");
//            }
//         }
//        }catch (Exception e){
//            e.printStackTrace();
//            ZnProfitHistory znProfitHistory = new ZnProfitHistory();
//            znProfitHistory.setId(profitId);
//            znProfitHistory.setState(2);
//            znProfitHistory.setResult("计算异常，请联系管理员");
//            znProfitHistoryMapper.updateZnProfitHistory(znProfitHistory);
//            throw  new ServiceException("计算异常，请联系管理员");
//        }
//    }
    @Override
    public void run() {
        znProfitDetailService.computeProfit(tenanId,profitId);
    }
}
